<?php
namespace app\admin\controller;
use app\common\controller\Adminbase;
use \think\Loader;
use \think\Db;
use \think\Request;

// +----------------------------------------------------------------------
// | XpCms
// +----------------------------------------------------------------------
// | Copyright (c) 2021-2099
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Mercurio（Xp） <725668993@qq.com>
// +----------------------------------------------------------------------

/*
** 表单 控制器
*/

class Form extends Adminbase {
	private static $_form 	= null; 	// 数据表对象
	
	// 优先加载
	public function _initialize() {
		parent::_initialize();
		
		// 实例化数据表模型
		self::$_form 	= Loader::model('Form');
		
	}
	
	// 表单 列表
	public function index() {
	    
	    // 当前页
		$nowPage = 1;
		if(isset($_GET['page']) && $_GET['page']){
			$nowPage = input('param.page/d');
			$nowPage = $nowPage > 0 ? $nowPage : 1;
		}
		
		$where = array();
		
		if(input('param.keyword')){
		    $keyword = input('param.keyword');
		    $this -> assign('keyword', $keyword);
		    $where['fname']=array('like','%'.$keyword.'%');
		}
		
		// 每页显示条数，默认 10 条
		$pagesize=input('param.page_size')?input('param.page_size'):10;
		$this -> assign('pagesize', pagesize($pagesize));
		
		$lists = self::$_form -> formLists($where, $nowPage, $pagesize);
		
		
		$this -> assign('lists', $lists['lists']);
		$this -> assign('page', $lists['page']);
	    
		
		
		return view('index');
	}
	
	// 新增表单页面
	public function add() {
		
		return view('add');
	}
	
	// 保存新增表单
	public function addsave() {
		
		$inputs = input('post.');
		
		// 使用模型验证器进行验证
		$this -> checkNameAdd($inputs);
		
		// 处理时间
		$inputs['create_time'] = time();
		$inputs['update_time'] = time();
		$inputs['fcode'] = get_auto_code(self::$_form -> getLastCode());
		
		$prefix = config('database.prefix');
		
		// 保存数据
		$fcode = Db::name('form')->insertGetId($inputs);
		if(empty($fcode)){
			$this -> success('添加表单失败！');
		}
		Db::execute("INSERT INTO `".$prefix."formfield` (`fcode`,`field`,`name`,`isrequire`,`issystem`) VALUES ( '".$inputs['fcode']."', 'name', '姓名', '0', '1')");
		Db::execute("INSERT INTO `".$prefix."formfield` (`fcode`,`field`,`name`,`isrequire`,`issystem`) VALUES ( '".$inputs['fcode']."', 'phone', '电话', '1', '1')");
		Db::execute("INSERT INTO `".$prefix."formfield` (`fcode`,`field`,`name`,`isrequire`,`issystem`) VALUES ( '".$inputs['fcode']."', 'content', '内容', '0', '1')");
		Db::execute("INSERT INTO `".$prefix."formfield` (`fcode`,`field`,`name`,`isrequire`,`issystem`) VALUES ( '".$inputs['fcode']."', 'source', '来源', '0', '1')");
		
		if ($fcode  !==false) {
            $this->success('添加表单成功', 'index');
        }else{
            $this->error('添加表单失败');
        }
	}
	
	// 编辑表单页面
	public function edit() {
		
		$id = input('param.id/d');
		if(!$id){
			$this -> error('参数错误');
		}
		
		$lists = self::$_form -> getFormDetail($id);
		if(!$lists){
			$this -> error('参数错误');
		}
		
		$this -> assign('lists', $lists);
		return view('add');
	}
	
	// 保存编辑表单
	public function editsave() {
		
		$inputs = input('post.');
		
		$id = (int) $inputs['id'];
		if(!$id){
			$this -> error('参数错误');
		}
		
		// 使用模型验证器进行验证
		$this -> checkNameAdd($inputs);
		
		$find = self::$_form -> where(array('id' => $id)) -> value('id');
		if(!$find){
			$this -> error('参数错误');
		}
		
		// 编辑时间
		$inputs['update_time'] = time();
		
		// 保存数据
		unset($inputs['id']);
		if(self::$_form -> save($inputs, array('id' => $id))){
			$this -> success('操作成功', 'index');
		}
		
		$this -> error('操作失败或没有数据可更新');
	}
	
	// 编辑表单状态
	public function editstatus() {
		
		$id = input('post.id/d');
		if(!$id){
		    return ['error'=>1,'msg'=>'参数错误'];
		}
		
		$result = self::$_form -> editStatus($id);
		if($result){
		    return ['error'=>0,'msg'=>'操作成功'];
		}
	    return ['error'=>1,'msg'=>'操作失败'];
	}
	
	// 删除表单
	public function deletes() {
		
		$id = input('post.id/d');
		if(!$id){
			return ['error'=>1,'msg'=>'参数错误'];
		}
		
		$result = self::$_form -> deletes($id);
		if($result['status'] == 1){
		    return ['error'=>0,'msg'=>'删除成功!'];
		}
        return ['error'=>1,'msg'=>$result['msg']];
	}
	
	//批量删除表单
    public function selectDel(){
        $id = input('post.id');
        if(!$id){
			return ['error'=>1,'msg'=>'ID不存在'];
		}
		$ids = explode(',', $id);
		for ($i = 0; $i < count($ids); $i++) {
	        $result = self::$_form -> deletes($ids[$i]);
    		if($result['status'] == 1){
    		}else{
    	        return ['error'=>1,'msg'=>$result['msg']];
    		}
		}
		return ['error'=>0,'msg'=>'删除成功!'];
    }
	
		// 验证新增数据 name 是否重复添加
	private function checkNameAdd($data) {
		$checkData = array('fname' => $data['fname']);
		$find = self::$_form -> where($checkData) -> find();
		if($find){
			$this -> error('同样的记录已经存在');
		}
		return true;
	}
	
	public function field(){

        $sysfield = array('name','phone','content','source');

        $list = Db::name('formfield')
            ->where("fcode",'=',input('id'))
            ->order('id asc')
            ->select();
        foreach ($list as $k=>$v){

            if(in_array($v['field'],$sysfield)){
                $list[$k]['delStatus']=1;//不可删除
            }else{
                $list[$k]['delStatus']=0;//可删除
            }
        }
        $this->view->assign('list'     , $list);
        $this->view->assign('fcode' , input('id'));
        return $this->view->fetch();
    }
    
    //添加字段
    public function fieldAdd(){
        $this->view->assign('fcode',input('fcode'));
        $this->view->assign('info',null);
        $this->view->assign('fieldInfo',null);
        return $this->view->fetch();
    }
    
    //添加字段保存
    public function fieldAddPost(){
        if(request()->isPost()){
            $data = input('post.');
            $fieldName=$data['field'];
            $prefix=config('database.prefix');
            $tablename=$prefix.'message';
            $Fields=Db::getTableFields($tablename);
            if(in_array($fieldName,$Fields)){
                $this->error('字段名已经存在！');
            }
            $addfieldsql =$this->get_tablesql($data,'add');
            $model = Db::name('formfield');
            if ($model->insert($data) !==false) {
                $model->execute($addfieldsql);
                $this->success('添加成功！', url('field',array('id'=>input('post.fcode'))));
            } else {
                $this->error('添加失败！');
            }
        }
    }
    
    //编辑字段
    public function fieldEdit(){
        $model = Db::name('formfield');
        $id = input('id');
        if(empty($id)){
            $this->error('缺少必要的参数！');
        }
        $fieldInfo = $model
            ->where('id','=',$id)
            ->find();
        $this->view->assign('info',$fieldInfo);
        $this->view->assign('fcode', input('fcode'));
        return $this->view->fetch('fieldadd');
    }
    
    //编辑字段保存
    public function fieldEditPost(){
        if(request()->isPost()){
            $data = Request::instance()->except('oldfield');
            $oldfield = input('oldfield');
            $fieldName = $data['field'];
            $prefix=config('database.prefix');
            if($this->_iset_field($prefix.'message',$fieldName) && $oldfield!=$fieldName){
                $this->error('字段名重复！');
            }
            $editfieldsql =$this->get_tablesql(input(),'edit');

            $model = Db::name('formfield');

            if (false !== $model->update($data)) {
                $model->execute($editfieldsql);
                $this->success('修改成功！',url('field',array('id'=>input('fcode'))));
            } else {
                $this->error('修改失败！');
            }
        }
    }
    
    //删除字段
    public function fieldDel() {
        $id=input('id');
        $r = Db::name('formfield')->find($id);
        Db::name('formfield')->delete($id);

        $moduleid = $r['fcode'];

        $field = $r['field'];

        $prefix=config('database.prefix');
        $tablename=$prefix.'message';

        Db::name('formfield')->execute("ALTER TABLE `$tablename` DROP `$field`");

        return ['error'=>0,'msg'=>'删除成功！'];
    }
    
    protected function _iset_field($table,$field){
        $fields = Db::getTableFields($table);
        return array_search($field,$fields);
    }
    
    public function get_tablesql($info,$do){
        $comment = $info['name'];
        $moduleid = $info['fcode'];
        $field = $info['field'];
        $prefix = config('database.prefix');
        $tablename=$prefix.'message';
        if($do=='add'){
            $do = ' ADD ';
        }else{
            $oldfield = $info['oldfield'];
            $do =  " CHANGE `".$oldfield."` ";
        }
        $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 255 ) COMMENT '$comment'";
        return $sql;
    }
	
}
